package cn.com.ghy.android.widget.salemag;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.ghy.android.bean.LoginInfoBean;
import cn.com.ghy.android.bean.YGOrderBaseInfoBean;
import cn.com.ghy.android.bean.YGOrderDetailInfoBean;
import cn.com.ghy.android.bean.YGQueryInfoBean;
import cn.com.ghy.android.exception.DisposeException;
import cn.com.ghy.android.service.YgOrderOpeService;
import cn.com.ghy.android.style.CustomProgressDialog;
import cn.com.ghy.android.style.MenuTabContent;
import cn.com.ghy.android.util.CommonStatic;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.ComStaticApp;
import cn.com.ghy.android.widget.R;

public class SaleOrder extends TabActivity {
	private TabHost tabHost;

	private View appToolBar;
	private ImageButton btnList;
	private ImageButton btnBack;

	private EditText txtVkorg;
	private Button btnVkorg;
	private EditText txtVtweg;
	private Button btnVtweg;

	private TextView txtSpart;

	private EditText txtAuart;
	private Button btnAuart;

	private TextView txtVkbur;
	private TextView txtVkgrp;

	private EditText txtKunag;
	private Button btnKunag;
	private EditText txtKunnr;
	private Button btnKunnr;
	private EditText txtStrasno;
	private Button btnStrano;
	private EditText txtPernr;
	private Button btnPernr;

	private EditText txtBstkd;
	private Button btnBstdk;
	private Button btnVdatu;
	private EditText txtRemark;

	private Button[] buttons;
	private Map<Integer, KeyEditText> mapEditText = new HashMap<Integer, KeyEditText>();

	private ProgressDialog progressDialog;

	private TextView labTxtOrderTotalPrice;
	private ListView listOrderDetailList;

	private MenuTabContent.MenuBodyAdapter bodyAdapter;
	private MenuTabContent tabMenu;

	private Intent intent;

	private int mYear = 0, mMonth = 0, mDay = 0;

	private LoginInfoBean loginInfo;
	private Map<String, Object> map = new HashMap<String, Object>();
	private List<YGOrderBaseInfoBean> yGOrderBaseInfoBeanList = new ArrayList<YGOrderBaseInfoBean>();
	private List<YGOrderDetailInfoBean> yGOrderDetailInfoBeanList = new ArrayList<YGOrderDetailInfoBean>();
	private YGOrderBaseInfoBean yGOrderBaseInfoBean;
	private List<YGQueryInfoBean> yGQueryInfoBeanList;
	private Map<String, String> mapValue = new HashMap<String, String>();
	private int intentFlag = -1;
	private YGOrderDetailInfoBean yGOrderDetailInfoBean;
	private String result = "";
	private String orderid;

	private OrderDetailInfoAdapter orderDetailInfoAdapter;

	private HttpThread httpThread;

	private DisposeException disposeException;
	private Exception error;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sale_order);
		getSession();
		tabHost = this.getTabHost();
		TabWidget tabWidget = tabHost.getTabWidget();

		tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("基本信息")
				.setContent(R.id.layOrderBaseInfo));
		tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("订单明细")
				.setContent(R.id.layOrderDetail));
		setMenu(tabHost.getCurrentTabTag());
		for (int i = 0; i < tabWidget.getChildCount(); i++) {
			tabWidget.getChildAt(i).getLayoutParams().height = this.getWindowManager()
					.getDefaultDisplay().getHeight() / 16;
		}
		setToolBar();
		findView();
		init();
		addListener();
	}

	private void setToolBar() {
		appToolBar = findViewById(R.id.appToolBar);
		btnList = (ImageButton) appToolBar.findViewById(R.id.btnList);
		btnBack = (ImageButton) appToolBar.findViewById(R.id.btnBack);
	}

	@SuppressWarnings("unchecked")
	public void getSession() {
		disposeException = ((ComStaticApp) getApplication()).getDisposeException();
		loginInfo = ((ComStaticApp) this.getApplication()).getLoginInfo();
		intent = this.getIntent();
		intentFlag = intent.getIntExtra("intentFlag", -1);
		if (intentFlag == -1) {
			Toast.makeText(SaleOrder.this, "程序出现异常，请联系管理员解决！", Toast.LENGTH_LONG).show();
		} else if (intentFlag == CommonStatic.STATE_MOD) {
			orderid = intent.getStringExtra("orderid");
		}
		map = (Map<String, Object>) intent.getSerializableExtra("order");
		yGOrderBaseInfoBeanList = (List<YGOrderBaseInfoBean>) map.get("orderBase");
		yGOrderBaseInfoBean = yGOrderBaseInfoBeanList.get(0);
		yGOrderDetailInfoBeanList = (List<YGOrderDetailInfoBean>) map.get("orderDetail");
	}

	private void findView() {
		btnVkorg = (Button) findViewById(R.id.btnVkorg);
		btnVtweg = (Button) findViewById(R.id.btnVtweg);
		btnAuart = (Button) findViewById(R.id.btnAuart);
		btnKunag = (Button) findViewById(R.id.btnKunag);
		btnKunnr = (Button) findViewById(R.id.btnKunnr);
		btnStrano = (Button) findViewById(R.id.btnStrano);
		btnPernr = (Button) findViewById(R.id.btnPernr);
		btnBstdk = (Button) findViewById(R.id.btnBstdk);
		btnVdatu = (Button) findViewById(R.id.btnVdatu);

		txtVkorg = (EditText) findViewById(R.id.txtVkorg);
		txtVtweg = (EditText) findViewById(R.id.txtVtweg);
		txtAuart = (EditText) findViewById(R.id.txtAuart);
		txtKunag = (EditText) findViewById(R.id.txtKunag);
		txtKunnr = (EditText) findViewById(R.id.txtKunnr);
		txtStrasno = (EditText) findViewById(R.id.txtStrasno);
		txtPernr = (EditText) findViewById(R.id.txtPernr);
		txtBstkd = (EditText) findViewById(R.id.txtBstkd);
		txtRemark = (EditText) findViewById(R.id.txtRemark);

		mapEditText.put(R.id.btnVkorg, new KeyEditText("VKORG", txtVkorg));
		mapEditText.put(R.id.btnVtweg, new KeyEditText("VTWEG", txtVtweg));
		mapEditText.put(R.id.btnAuart, new KeyEditText("AUART", txtAuart));
		mapEditText.put(R.id.btnKunag, new KeyEditText("KUNAG", txtKunag));
		mapEditText.put(R.id.btnKunnr, new KeyEditText("KUNNR", txtKunnr));
		mapEditText.put(R.id.btnStrano, new KeyEditText("STRASNO", txtStrasno));
		mapEditText.put(R.id.btnPernr, new KeyEditText("PERNR", txtPernr));

		txtSpart = (TextView) findViewById(R.id.txtSpart);
		txtVkbur = (TextView) findViewById(R.id.txtVkbur);
		txtVkgrp = (TextView) findViewById(R.id.txtVkgrp);

		buttons = new Button[] { btnVkorg, btnVtweg, btnAuart, btnKunag, btnKunnr, btnStrano,
				btnPernr, btnBstdk, btnVdatu };

		labTxtOrderTotalPrice = (TextView) findViewById(R.id.labTxtOrderTotalPrice);
		listOrderDetailList = (ListView) findViewById(R.id.listOrderDetailList);
	}

	private void init() {
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		txtVkorg.setText(yGOrderBaseInfoBean.getVkorg() == null ? "" : yGOrderBaseInfoBean
				.getVkorg());
		txtVtweg.setText(yGOrderBaseInfoBean.getVtweg() == null ? "" : yGOrderBaseInfoBean
				.getVtweg());
		txtAuart.setText(yGOrderBaseInfoBean.getAuart() == null ? "" : yGOrderBaseInfoBean
				.getAuart());
		txtVkbur.setText(yGOrderBaseInfoBean.getVkbur());
		txtVkgrp.setText(yGOrderBaseInfoBean.getVkgrp());

		if (intentFlag == CommonStatic.STATE_MOD) {
			txtKunag.setText(yGOrderBaseInfoBean.getKunag() == null ? "" : yGOrderBaseInfoBean
					.getKunag());
			txtKunnr.setText(yGOrderBaseInfoBean.getKunnr() == null ? "" : yGOrderBaseInfoBean
					.getKunnr());
			txtStrasno.setText(yGOrderBaseInfoBean.getStrasno() == null ? "" : yGOrderBaseInfoBean
					.getStrasno());
			txtPernr.setText(yGOrderBaseInfoBean.getPernr() == null ? "" : yGOrderBaseInfoBean
					.getPernr());
			txtBstkd.setText(yGOrderBaseInfoBean.getBstkd() == null ? "" : yGOrderBaseInfoBean
					.getBstkd());
			btnBstdk.setText(yGOrderBaseInfoBean.getBstdk() == null ? "请选择采购日期"
					: yGOrderBaseInfoBean.getBstdk());
			btnVdatu.setText(yGOrderBaseInfoBean.getVdatu() == null ? "请选择交货日期"
					: yGOrderBaseInfoBean.getVdatu());
			txtRemark.setText(yGOrderBaseInfoBean.getRemark() == null ? "" : yGOrderBaseInfoBean
					.getRemark());
			yGOrderBaseInfoBean.setOrderid(orderid);
		}

		labTxtOrderTotalPrice.setText("0.00");

		orderDetailInfoAdapter = new OrderDetailInfoAdapter(this);
		listOrderDetailList.setAdapter(orderDetailInfoAdapter);
		listOrderDetailList.setOnItemClickListener(new OrderDataLisEvent());

		for (int i = 0; i < yGOrderDetailInfoBeanList.size(); i++) {
			orderDetailInfoAdapter.addOrder(yGOrderDetailInfoBeanList.get(i));
		}
	}

	private void addListener() {
		btnList.setOnClickListener(btnListenerEvent);
		btnBack.setOnClickListener(btnListenerEvent);
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				setMenu(tabId);
			}

		});
		for (int i = 0; i < buttons.length; i++) {
			buttons[i].setOnClickListener(btnListenerEvent);
		}
	}

	private View.OnClickListener btnListenerEvent = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btnVkorg :
				case R.id.btnVtweg :
					operate(v.getId());
					break;
				case R.id.btnAuart :
				case R.id.btnKunag :
					if ("".equals(txtVkorg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入销售组织", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtVtweg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入分销渠道", Toast.LENGTH_SHORT).show();
						break;
					}
					operate(v.getId());
					break;
				case R.id.btnKunnr :
					if ("".equals(txtVkorg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入销售组织", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtVtweg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入分销渠道", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtKunag.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入售达方", Toast.LENGTH_SHORT).show();
						break;
					}
					operate(v.getId());
					break;
				case R.id.btnStrano :
					if ("".equals(txtVkorg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入销售组织", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtVtweg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入分销渠道", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtKunag.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入售达方", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtKunnr.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入送达方", Toast.LENGTH_SHORT).show();
						break;
					}
					operate(v.getId());
					break;
				case R.id.btnPernr :
					if ("".equals(txtVkorg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入销售组织", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtVtweg.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入分销渠道", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtKunag.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入售达方", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtKunnr.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入送达方", Toast.LENGTH_SHORT).show();
						break;
					}
					if ("".equals(txtStrasno.getText().toString().trim())) {
						Toast.makeText(SaleOrder.this, "请输入送货地址", Toast.LENGTH_SHORT).show();
						break;
					}
					operate(v.getId());
					break;
				case R.id.btnBstdk :
					showDialog(R.id.btnBstdk);
					break;
				case R.id.btnVdatu :
					showDialog(R.id.btnVdatu);
					break;
				case R.id.btnList :
					openOptionsMenu();
					break;
				case R.id.btnBack :
					new AlertDialog.Builder(SaleOrder.this).setTitle("提示信息")
							.setMessage("确定要退出操作的订单?")
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dlg, int sumthin) {
									SaleOrder.this.finish();
								}
							}).setNeutralButton("取消", null).show();
					break;
				default :
					break;
			}
		}
	};

	private class OrderDataLisEvent implements AdapterView.OnItemClickListener {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			OrderDetailInfoAdapter orderInfoAdapter = (OrderDetailInfoAdapter) (parent.getAdapter());
			showAlertDialog(SaleOrder.this, position, orderInfoAdapter.getItem(position));

		}
	}

	private void operate(int opcode) {
		progressDialog = new CustomProgressDialog(SaleOrder.this);
		progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				httpThread.stopSendMsg();
			}
		});
		progressDialog.show();

		httpThread = new HttpThread(opcode);
		Thread thread = new Thread(httpThread);
		thread.start();
	}

	private class HttpThread implements Runnable {

		private int opcode;

		public HttpThread(int opcode) {
			this.opcode = opcode;
		}

		private boolean isSendMsg = true;

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			YgOrderOpeService service = new YgOrderOpeService();
			try {
				switch (opcode) {
					case R.id.btnVkorg :
					case R.id.btnVtweg :
					case R.id.btnAuart :
					case R.id.btnKunag :
					case R.id.btnKunnr :
					case R.id.btnStrano :
					case R.id.btnPernr :
						Iterator<Entry<Integer, KeyEditText>> it = mapEditText.entrySet()
								.iterator();
						while (it.hasNext()) {
							int key = it.next().getKey();
							String value = mapEditText.get(key).getEditText().getText().toString();
							mapValue.put(mapEditText.get(key).getKey(), value);
						}
						mapValue.put("SPART", txtSpart.getText().toString());
						mapValue.put("VKBUR", txtVkbur.getText().toString());
						mapValue.put("VKGRP", txtVkgrp.getText().toString());
						yGQueryInfoBeanList = service.GetSlt(mapValue, mapEditText.get(opcode)
								.getKey());
						break;
					case R.drawable.data_coll_menu_submit :
						if (intentFlag == CommonStatic.STATE_ADD) {
							result = "提交订单失败， 请检查所填信息是否正确";
							result = service.OrderAdd(yGOrderBaseInfoBeanList,
									yGOrderDetailInfoBeanList);
						} else if (intentFlag == CommonStatic.STATE_MOD) {
							result = "修改订单失败， 请检查所填信息是否正确";
							result = service.OrderEdit(yGOrderBaseInfoBeanList,
									yGOrderDetailInfoBeanList);
						}

						break;
					default :
						break;
				}
			} catch (Exception e) {
				opcode = CommonStatic.ERROR_CODE;
				error = e;
			}
			if (isSendMsg) {
				message.what = opcode;
				handler.sendMessage(message);
			}
		}

		public void stopSendMsg() {
			isSendMsg = false;
		}

		@SuppressWarnings("unused")
		public void openSendMsg() {
			isSendMsg = true;
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
				case R.id.btnVkorg :
				case R.id.btnVtweg :
				case R.id.btnAuart :
				case R.id.btnKunag :
				case R.id.btnKunnr :
				case R.id.btnStrano :
				case R.id.btnPernr :
					Bundle bundle = new Bundle();
					bundle.putSerializable("queryInfoList", (Serializable) yGQueryInfoBeanList);
					bundle.putInt("btnRId", msg.what);
					bundle.putString("key", mapEditText.get(msg.what).getKey());
					bundle.putString("value", mapEditText.get(msg.what).getEditText().getText()
							.toString());
					bundle.putSerializable("mapValue", (Serializable) mapValue);
					intent = new Intent(SaleOrder.this, SaleOrderBaseInfoQuery.class);
					intent.putExtras(bundle);
					SaleOrder.this.startActivityForResult(intent,
							R.layout.sale_order_baseinfo_query);
					break;
				case R.drawable.data_coll_menu_submit :
					if ("OK".equalsIgnoreCase(result)) {
						if (intentFlag == CommonStatic.STATE_ADD) {
							result = "提交订单成功";
						} else if (intentFlag == CommonStatic.STATE_MOD) {
							result = "修改订单成功";
						}
						new AlertDialog.Builder(SaleOrder.this).setTitle("提示信息").setMessage(result)
								.setPositiveButton("确定", new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dlg, int sumthin) {
										SaleOrder.this.finish();
									}
								}).show();
					} else {
						if (intentFlag == CommonStatic.STATE_ADD) {
							result = "提交订单失败：" + result;
						} else if (intentFlag == CommonStatic.STATE_MOD) {
							result = "修改订单失败：" + result;
						}
						new AlertDialog.Builder(SaleOrder.this).setTitle("提示信息").setMessage(result)
								.setPositiveButton("关闭", null).show();
					}
					break;
				case CommonStatic.ERROR_CODE :
					disposeException.handleException(error);
					break;
				default :
					break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case R.layout.sale_order_baseinfo_query :
				if (resultCode == RESULT_OK) {
					Bundle bundleForResult = data.getExtras();
					int btnRId = bundleForResult.getInt("btnRId");
					String value = bundleForResult.getString("value");
					KeyEditText keyEditText = mapEditText.get(btnRId);
					if (keyEditText != null) {
						keyEditText.getEditText().setText(value);
					}
				}
				break;
			case R.layout.sale_order_detail_info :
				if (resultCode == RESULT_OK) {
					Bundle bundleForResult = data.getExtras();
					yGOrderDetailInfoBean = (YGOrderDetailInfoBean) bundleForResult
							.getSerializable("yGOrderDetailInfoBean");
					int position = -1;
					position = bundleForResult.getInt("position");
					if (position != -1) {
						orderDetailInfoAdapter.modify(position, yGOrderDetailInfoBean);
					} else {
						orderDetailInfoAdapter.addOrder(yGOrderDetailInfoBean);
					}

				}
				break;
			default :
				break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(SaleOrder.this).setTitle("提示信息").setMessage("确定要退出操作的订单?")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dlg, int sumthin) {
							SaleOrder.this.finish();
						}
					}).setNeutralButton("取消", null).show();
		}
		return true;
	}

	private void setMenu(String tabId) {
		String flag = "提交订单";
		if (intentFlag == CommonStatic.STATE_MOD) {
			flag = "修改订单";
		}
		if ("tab1".equals(tabId)) {
			bodyAdapter = new MenuTabContent.MenuBodyAdapter(this, new String[] { flag },
					new int[] { R.drawable.data_coll_menu_submit }, 13, getResources().getColor(
							R.color.white));
		} else if ("tab2".equals(tabId)) {
			bodyAdapter = new MenuTabContent.MenuBodyAdapter(this, new String[] { "添加", "删除全部",
					flag }, new int[] { R.drawable.menu_add, R.drawable.menu_delete,
					R.drawable.data_coll_menu_submit }, 13, getResources().getColor(R.color.white));
		}

		tabMenu = new MenuTabContent(this, //
				new BodyClickEvent(tabId), //
				getResources().getColor(R.color.MenuBackGroundColor),// 
				R.style.PopupAnimation);// 

		tabMenu.update();
		tabMenu.SetBodyAdapter(bodyAdapter);
	}

	private class BodyClickEvent implements OnItemClickListener {
		private String tabId = "";

		public BodyClickEvent(String tabId) {
			super();
			this.tabId = tabId;
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			tabMenu.SetBodySelect(position, Color.GRAY);
			if ("tab1".equals(tabId)) {
				switch (position) {
					case 0 : // 
						submit();
						break;
				}
			} else if ("tab2".equals(tabId)) {
				switch (position) {
					case 0 : // 
						intent = new Intent(SaleOrder.this, SaleOrderDetailInfo.class);
						SaleOrder.this.startActivityForResult(intent, //
								R.layout.sale_order_detail_info);
						break;
					case 1 : // 
						if (orderDetailInfoAdapter.getItemAll() != null //
								&& orderDetailInfoAdapter.getItemAll().size() > 0) {
							new AlertDialog.Builder(SaleOrder.this)
									.setTitle("提示信息")
									.setMessage("确定删除全部订单信息?")
									.setPositiveButton("确定", new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog, int whichButton) {
											orderDetailInfoAdapter.removeAll();
										}
									})
									.setNeutralButton("关闭", new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dlg, int sumthin) {
										}
									}).show();
						} else {
							Toast.makeText(SaleOrder.this, "没有要删除的订单信息!", Toast.LENGTH_SHORT)
									.show();
						}
						break;
					case 2 :
						submit();
						break;
					default :
						break;
				}
			}
			if (null != tabMenu) {
				if (tabMenu.isShowing()) {
					tabMenu.dismiss();
				}
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("menu");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (tabMenu != null) {
			if (tabMenu.isShowing()) {
				tabMenu.dismiss();
			} else {
				int toolBarHeight = appToolBar.getHeight();
				tabMenu.showAtLocation(findViewById(R.id.appToolBar), Gravity.BOTTOM, 0,
						toolBarHeight);
			}
		}
		return false;
	}

	private class OrderDetailInfoAdapter extends BaseAdapter {

		private Context context;
		private List<YGOrderDetailInfoBean> list = new ArrayList<YGOrderDetailInfoBean>();

		public OrderDetailInfoAdapter(Context context) {
			this.context = context;
		}

		public int getCount() {
			return list.size();
		}

		public YGOrderDetailInfoBean getItem(int position) {
			return list.get(position);
		}

		public List<YGOrderDetailInfoBean> getItemAll() {
			return list;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			String inflater = Context.LAYOUT_INFLATER_SERVICE;
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(inflater);
			LinearLayout linearLayout = null;
			YGOrderDetailInfoBean bean = list.get(position);
			linearLayout = (LinearLayout) layoutInflater.inflate( //
					R.layout.sale_order_detail_lay, null);
			TextView textView = (TextView) linearLayout.findViewById(R.id.labBismt);
			textView.setText(bean.getBismt());

			textView = (TextView) linearLayout.findViewById(R.id.labUnit);
			textView.setText(bean.getUnit());

			textView = (TextView) linearLayout.findViewById(R.id.labMatnr);
			textView.setText(bean.getMatnr());

			textView = (TextView) linearLayout.findViewById(R.id.labOrdernum);
			textView.setText(bean.getOrdernum());

			textView = (TextView) linearLayout.findViewById(R.id.labOrderprice);
			textView.setText(bean.getOrderprice() + "元");

			textView = (TextView) linearLayout.findViewById(R.id.labDnm);
			textView.setText(bean.getDnm());

			textView = (TextView) linearLayout.findViewById(R.id.labIsfin);

			textView = ((TextView) linearLayout.findViewById(R.id.labTotalprice));
			textView.setText(bean.getTotalprice() + "元");
			return linearLayout;
		}

		public void addOrder(YGOrderDetailInfoBean orderDetail) {
			for (int i = 0; i < list.size(); i++) {
				if (orderDetail.getBismt().equals(list.get(i).getBismt())) {
					Toast.makeText(SaleOrder.this, "SKU:" + orderDetail.getBismt() + "不能重复!",
							Toast.LENGTH_SHORT).show();
					return;
				}
			}
			list.add(orderDetail);
			totalPriceCount(list);
			notifyDataSetChanged();
		}

		public void remove(int index, YGOrderDetailInfoBean orderDetail) {
			if (index < 0)
				return;
			list.remove(index);
			totalPriceCount(list);
			notifyDataSetChanged();
		}

		public void modify(int index, YGOrderDetailInfoBean orderDetail) {
			if (index < 0)
				return;
			list.remove(index);
			list.add(index, orderDetail);
			totalPriceCount(list);
			notifyDataSetChanged();
		}

		private void totalPriceCount(List<YGOrderDetailInfoBean> list) {
			double totalPrice = 0;
			for (YGOrderDetailInfoBean orderDetail : list) {
				totalPrice += Double.parseDouble(orderDetail.getTotalprice());
			}
			java.text.DecimalFormat df = new java.text.DecimalFormat("######0.00");
			labTxtOrderTotalPrice.setText(df.format(totalPrice));
		}

		public void removeAll() {
			if (null != list && list.size() > 0) {
				list.removeAll(list);
				notifyDataSetChanged();
				labTxtOrderTotalPrice.setText("0.00");
			}
		}
	}

	private void showAlertDialog(final Context context, final int position, //
			final YGOrderDetailInfoBean orderDetail) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("提示信息:");
		builder.setMessage("SKU编号：" + orderDetail.getBismt());
		builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				intent = new Intent(SaleOrder.this, SaleOrderDetailInfo.class);
				Bundle bundle = new Bundle();
				bundle.putInt("position", position);
				bundle.putSerializable("yGOrderDetailInfoBean", orderDetail);
				intent.putExtras(bundle);
				SaleOrder.this.startActivityForResult(intent, R.layout.sale_order_detail_info);
			}
		});
		builder.setNegativeButton("删除", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				orderDetailInfoAdapter.remove(position, orderDetail);
			}
		});
		builder.show();
	}

	public void submit() {
		if (!createOrder()) {
			return;
		}

		String msg = "确认提交订单?";
		if (intentFlag == CommonStatic.STATE_MOD) {
			msg = "确认提交修改后的订单?";
		}
		new AlertDialog.Builder(SaleOrder.this).setTitle("提示信息").setMessage(msg)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dlg, int sumthin) {
						operate(R.drawable.data_coll_menu_submit);
					}
				}).setNegativeButton("取消", null).show();
	}

	private boolean createOrder() {
		boolean flag = false;
		String vkorg = txtVkorg.getText().toString().trim();
		if ("".equals(vkorg)) {
			Toast.makeText(SaleOrder.this, "请输入销售组织", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String vtweg = txtVtweg.getText().toString().trim();
		if ("".equals(vtweg)) {
			Toast.makeText(SaleOrder.this, "请输入分销渠道", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String auart = txtAuart.getText().toString().trim();
		if ("".equals(auart)) {
			Toast.makeText(SaleOrder.this, "请输入订单类型", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String kunag = txtKunag.getText().toString().trim();
		if ("".equals(kunag)) {
			Toast.makeText(SaleOrder.this, "请输入售达方", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String kunnr = txtKunnr.getText().toString().trim();
		if ("".equals(kunnr)) {
			Toast.makeText(SaleOrder.this, "请输入送达方", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String strasno = txtStrasno.getText().toString().trim();
		if ("".equals(strasno)) {
			Toast.makeText(SaleOrder.this, "请输入送货地址", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String pernr = txtPernr.getText().toString().trim();
		if ("".equals(pernr)) {
			Toast.makeText(SaleOrder.this, "请输入业务员", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String bstkd = txtBstkd.getText().toString().trim();
		if ("".equals(bstkd)) {
			Toast.makeText(SaleOrder.this, "请输入采购单号", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String bstdk = btnBstdk.getText().toString().trim();
		if ("".equals(bstdk) || "请选择采购日期".equals(bstdk)) {
			Toast.makeText(SaleOrder.this, "请选择采购日期", Toast.LENGTH_SHORT).show();
			return flag;
		}
		String vdatu = btnVdatu.getText().toString().trim();
		if ("".equals(vdatu) || "请选择交货日期".equals(vdatu)) {
			Toast.makeText(SaleOrder.this, "请选择交货日期", Toast.LENGTH_SHORT).show();
			return flag;
		}

		yGOrderDetailInfoBeanList = orderDetailInfoAdapter.getItemAll();

		if (yGOrderDetailInfoBeanList.size() == 0) {
			Toast.makeText(SaleOrder.this, "请添加订单明细内容!", Toast.LENGTH_SHORT).show();
			return flag;
		}

		yGOrderBaseInfoBean.setVkorg(vkorg);
		yGOrderBaseInfoBean.setVtweg(vtweg);
		yGOrderBaseInfoBean.setAuart(auart);
		yGOrderBaseInfoBean.setKunag(kunag);
		yGOrderBaseInfoBean.setKunnr(kunnr);
		yGOrderBaseInfoBean.setStrasno(strasno);
		yGOrderBaseInfoBean.setPernr(pernr);
		yGOrderBaseInfoBean.setBstkd(bstkd);
		yGOrderBaseInfoBean.setBstdk(bstdk);
		yGOrderBaseInfoBean.setVdatu(vdatu);
		yGOrderBaseInfoBean.setRemark(txtRemark.getText().toString().trim());
		yGOrderBaseInfoBean.setSpart(txtSpart.getText().toString().trim());
		yGOrderBaseInfoBean.setVkbur(txtVkbur.getText().toString().trim());
		yGOrderBaseInfoBean.setVkgrp(txtVkgrp.getText().toString().trim());
		yGOrderBaseInfoBean.setSaof(loginInfo.getSaof());
		yGOrderBaseInfoBean.setCuser(loginInfo.getPernr());

		flag = true;
		return flag;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final int btnId = id;
		DatePickerDialog datePickerDialog = new DatePickerDialog(this, //
				new DatePickerDialog.OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						String date = CommonUtil.formateDate(year, monthOfYear, dayOfMonth);
						switch (btnId) {
							case R.id.btnBstdk :
								btnBstdk.setText(date);
								break;
							case R.id.btnVdatu :
								btnVdatu.setText(date);
								break;
							default :
								break;
						}

					}

				}, mYear, mMonth, mDay);
		return datePickerDialog;
	}

	private class KeyEditText {
		private String key;
		private EditText editText;

		public KeyEditText(String key, EditText editText) {
			this.key = key;
			this.editText = editText;
		}

		public String getKey() {
			return key;
		}

		public EditText getEditText() {
			return editText;
		}
	}
}
